package com.chanceit.ssss.service;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.utils.lg;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.data.DataSources;

public class MyService extends Service {
	public MyService() {
	}

	@Override
	public IBinder onBind(Intent intent) {
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onDestroy() {
		bThreadRunning = false;
		if (t != null) {
			t.interrupt();
			t = null;
		}
		super.onDestroy();
	}

	boolean bThreadRunning = true;
	protected String TAG = "myService";
	Thread t;

	public void onCreate() {
//		t = new Thread(new Runnable() {
//			@Override
//			public void run() {
//				while (bThreadRunning) {
//					try {
//						Thread.sleep(1000*30);
//						getToDoNum();
//					} catch (InterruptedException e) {
//					}
//				}
//			}
//		});
//		t.start();
	}

	void getToDoNum() {
		DataSources ds = new DataSources();
		ds.getReminder(null, 0, new AjaxCallBack<String>() {

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				lg.i(TAG, "" + t);
				try {
					JSONObject ja;
					ja = new JSONObject(t);
					// ja.optInt("inshopuser") > 0
					// reserve//TODO 碰撞 预约 到店 通知栏提醒
					send("tip:hit", "more");
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	@SuppressWarnings("deprecation")
	public void send(String title, String content) {

		// 1.得到NotificationManager
		NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// 2.实例化一个通知，指定图标、概要、时间
		Notification n = new Notification(R.drawable.ic_launcher, "通知",
				System.currentTimeMillis());
		// 3.指定通知的标题、内容和intent
		Intent intent = new Intent(ActivityActionName.LOGIN);
		intent.setAction(ActivityActionName.SafeActivity);
		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
		n.setLatestEventInfo(this, title, content, pi);
		// 指定声音
		// n.defaults = Notification.DEFAULT_SOUND;
		// 4.发送通知
		nm.notify(1, n);
	}
}
